import React, { useEffect, useRef, useState,forwardRef,useImperativeHandle } from "react";
import { Modal,Form,Button,Spin,Select,Image,Input, message} from 'antd';
import LlxTable from './LlxTable'
import LlxForm from './LlxForm/index'
import UploadPicture from './Upload/index'
import AudioUpload from './Upload/audio'
import LlxPlay from 'components/LlxPlay'
import ImportWord from 'components/LlxPushData/word'
import StartGame from 'components/Game'
import RelacePhoto from 'components/LlxPushData/replacePhoto'
import {updateGraph} from 'api/index'
const {Option} = Select



const PreviewAudio = forwardRef((props, ref) => {
  const {isModalVisible, setIsModalVisible,userName,dictionaries,disabled} = props

  const [dataSource,setDataSource] = useState([])
  const [pictureList,setPictureList] = useState([])
  const [coorList,setCoorList] = useState([])
  const [pictureData,setPictureData] = useState({})
  const [spinning,setSpinning] = useState(false)
  const [isModalVisiblePhoto,setIsModalVisiblePhoto] = useState(false)
  const [isModalVisibleGame,setIsModalVisibleGame] = useState(false)
  const [isModalVisibleWord,setIsModalVisibleWord] = useState(false)

 const [form] = Form.useForm()
 const img = useRef(null)
   
 useImperativeHandle(ref, () => ({
  form,setDataSource
}));

 useEffect(()=>{
  if(form.getFieldValue().id){
    setDataSource(form.getFieldValue().gameItems)
  }

  return ()=>form.resetFields()
 },[isModalVisible])// eslint-disable-line react-hooks/exhaustive-deps

 const formItem = [

  {label: '引导文字',type:'input',name: 'guideText', span: 6},
  {label: '引导语音', name: 'guideAudio', span: 6 ,render:()=>{
    return  <AudioUpload  audio={form.getFieldValue().guideAudio} style={{marginLeft:'20px'}} setAudio={value=>form.setFieldsValue({...form.getFieldValue(),guideAudio:value})}></AudioUpload>
  }},
  {label: '解析文字',type:'input',name: 'analysisText', span: 6},
  {label: '解析语音', name: 'analysisAudio', span: 6 ,render:()=>{
    return  <AudioUpload  audio={form.getFieldValue().analysisAudio} style={{marginLeft:'20px'}} setAudio={value=>form.setFieldsValue({...form.getFieldValue(),analysisAudio:value})}></AudioUpload>
  }},
  {label: '圈图', name: 'pictureUrl' , span: 6 ,rules:[
    {
      required: true,
      message:'请上传圈图'
    }
  ],render: () => {
    return   <UploadPicture disabled={form.getFieldValue().id||disabled} pictureUrl={form.getFieldValue().pictureUrl} setPhoto={(value)=>form.setFieldsValue({...form.getFieldValue(),pictureUrl:value})}></UploadPicture>
  }},
  {label: '背景音乐', name: 'backgroundMusic', span: 6 ,render:()=>{
  return  <AudioUpload  audio={form.getFieldValue().backgroundMusic} style={{marginLeft:'20px'}} setAudio={value=>form.setFieldsValue({...form.getFieldValue(),backgroundMusic:value})}></AudioUpload>
  }},
  {label: '新增', name: 'addArea', span: 12,render:()=>{
  return  <>
  <Button onClick={addArea} type={'primary'}>新增区域</Button>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
  <Button onClick={addSite} type={'primary'}>新增考点</Button>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
  <Button onClick={onOk} type={'primary'}>保存圈图</Button>
  </>
  }},
 ]

 const columns = [
  {title: '序号', dataIndex: 'sort',key: 'sort', align: 'center',width:70},
  {title: '考点', dataIndex: 'examination',key: 'examination', align: 'center'},
  {title: '音频', dataIndex: 'audioUrl',key: 'audioUrl',width:80, align: 'center',render:(text)=>{
    return text?<LlxPlay audioUrl={text}></LlxPlay>:''
  }},
  {title: '图片', dataIndex: 'pictureUrl',key: 'pictureUrl', align: 'center',render:(text,row)=>{
   return row.pictureUrl&&row.pictureUrl.length?<>
   {row.pictureUrl.map(i=>{
     return <Image
     key={i}
     width={50}
     src={i}
   />
   })}
   <span className="text-link" onClick={()=>checkPhoto(row)}>修改图片</span>
   </>:''
  }},
  {title: '类型', dataIndex: 'correctError',key: 'correctError', align: 'center',render:(text,row)=>{
    return   <Select placeholder={'选择'} onChange={e=>row.correctError=e} defaultValue={row.correctError} style={{ width: 120 }}>
    <Option value={0}>错误</Option>
    <Option value={1}>正确</Option>
    <Option value={2}>讲解</Option>
  </Select>
  }},
  {title: '区域语音', dataIndex: 'interfereAudio',key: 'interfereAudio', align: 'center',render:(text,row)=>{
    return <AudioUpload audio={row.interfereAudio} style={{marginLeft:'20px'}} setAudio={value=>row.interfereAudio=value}></AudioUpload>
   }},
  {title: '区域文本', dataIndex: 'interfereText',key: 'interfereText', align: 'center',render:(text,row)=>{
    return <Input placeholder="输入" defaultValue={row.interfereText} onChange={(e)=>row.interfereText=e.target.value}></Input>
   }},
  {title: '区域数', dataIndex: 'answers',key: 'answers',width:70, align: 'center',render:(text,row)=>{
    return row.answers.length
   }},
  {title: '编辑', dataIndex: 'active',key: 'active', align: 'center',render:(text,row)=>{
    return <div>
      <span className="text-link" onClick={()=>startCoor(row)}>圈图</span>&nbsp;&nbsp;&nbsp;
      <span className="text-link text-color-red" onClick={()=>removeCoor(row)}>移除</span>
    </div>
  }},
 ]

  // 1.保存数据
const onOk = () => {
  form.validateFields().then(async()=>{
    if(!dataSource.length){
      message.error("请至少添加一个区域呀")
      return
    }
    setSpinning(true)
   const {globalType,pictureUrl,id,analysisAudio,guideAudio,backgroundMusic,guideText,analysisText} = form.getFieldValue()
    

   if(img.current){
    const data = {
      pictureWidth: img.current.naturalWidth,
      pictureHeight: img.current.naturalHeight,
      pictureUrl,
      circles: dataSource?.map((i, index) => {
        return {
          answers: i.answers.map((item, index) => {
            return { coordinate: item.circleId?JSON.stringify(item.coordinate):JSON.stringify(item)}
          }),
          pictureUrl: i.pictureUrl,
          examination: i.examination,
          audioUrl: i.audioUrl,
          wordId: i.wordId,
          sort: index + 1,
          interfereText: i.interfereText,
          interfereAudio: i.interfereAudio,
          correctError: i.correctError
        }
      }) || [],
      globalType: globalType||props.globalType||1,
      analysisText,
      analysisAudio,
      guideText,
      guideAudio,
      backgroundMusic,
      id: id || ''
    }

    const res = await updateGraph(data)

    if(props.getSubjectGameId){
      props.getSubjectGameId(res.result)
    }

     message.success('操作成功')
     
     form.resetFields()

     setDataSource([])

     onCancel()
   }

   setSpinning(false)
  }).catch(err=>{
    setSpinning(false)
  })
}
  // 2.新增考点
const addSite = () => {
  if(!form.getFieldValue().pictureUrl){
    message.error('请先上传圈图图片')
    return
  }
  setIsModalVisibleWord(true)
}
// 2.1导入单词
const setSelectWords = (value,data) => {

  setDataSource(value=>[...value,{
    wordId:data.id,
    wdWordPictures:data.wdWordPictures,
    pictureUrl:[data.wdWordPictures[0].pictureUrl],
    audioUrl:data.audioUrl,
    examination:data.wordName,
    correctError:1,
    key:value.length+1,
    id:value.length+1,
    sort:value.length+1,
    interfereAudio:'',
    interfereText:'',
    answers:[]
  }])

  setIsModalVisibleWord(false)
}
  // 3.新增区域
const addArea = () => {
  if(!form.getFieldValue().pictureUrl){
    message.error('请先上传圈图图片')
    return
  }
  setDataSource(value=>[...value,{
    correctError:2,
    sort:value.length+1,
    key:value.length+1,
    id:value.length+1,
    interfereAudio:'',
    interfereText:'',
    answers:[]
  }])
}
  // 4.修改图片
const checkPhoto = (value) => {
setPictureData(value)
setPictureList(value.wdWordPictures)
setIsModalVisiblePhoto(true)
}
// 4.1替换
const getSelectPhoto = (value) => {
const data = dataSource
data.filter(i=>i.wordId===pictureData.wordId)[0].pictureUrl=value
}
  // 5.移除圈图
const removeCoor = (value) => {
  setDataSource(i=>i.filter(i=>i.sort!==value.sort))
}
  // 6.开始圈图
const startCoor = (value) => {
  setPictureData(value)
  if(form.getFieldValue().id){
   setCoorList(value.answers.map(i=>i.coordinate)||[])
  } else {
    setCoorList(value.answers||[])
  }
  setIsModalVisibleGame(true)
}
// 6.1
const getNewCoor= (value) => {
  const data = dataSource
  data.filter(i=>i.sort===pictureData.sort)[0].answers=value
}
  // 7.返回
const onCancel = () => {

  form.resetFields()
  setDataSource([])
  setIsModalVisible(false)
}

  return  isModalVisible?<Modal wrapClassName="modal-full" width={1200} destroyOnClose title={'圈图游戏'}  visible={isModalVisible}  onCancel={onCancel}>
     

  <Spin tip="正在提交..." spinning={spinning}>
   {/* 头部表单 */}
   <LlxForm preserve={true} form={form} labelCol={8} formItem={formItem} />


   {/* 数据表格 */}
   <LlxTable
     selectedRowShow={false}
     height={300}
     paginationHide={true}
     columns={columns}
     dataSource={dataSource}/>
     </Spin>

{/* 替换图片 */}
 <RelacePhoto getSelectPhoto={getSelectPhoto} data={pictureList} isModalVisible={isModalVisiblePhoto} setIsModalVisible={setIsModalVisiblePhoto}></RelacePhoto>

{/* 导入考点单词 */}
<ImportWord title={'导入考点单词'} isModalVisible={isModalVisibleWord} dictionaries={dictionaries} userName={userName} setSelectWords={setSelectWords} multipleType={false} setIsModalVisible={setIsModalVisibleWord}></ImportWord>

{/* 圈图 */}
<StartGame width={form.getFieldValue().pictureWidth} getNewCoor={getNewCoor} pictureUrl={form.getFieldValue().pictureUrl} coorList={coorList} setCoorList={setCoorList} isModalVisible={isModalVisibleGame} setIsModalVisible={setIsModalVisibleGame} ></StartGame>

<img style={{opacity:0,width:'1px',height:'1px'}} src={form.getFieldValue().pictureUrl} ref={img} alt="" />


</Modal>:null

})
export default PreviewAudio